package com.GroupSix.controller;

import com.GroupSix.entity.QuestionBankEntity;
import com.GroupSix.service.QuestionBankService;
import com.GroupSix.tool.ExcelImporter;
import com.GroupSix.vo.QuestionBankEntityVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;


@Slf4j
@RestController
@RequestMapping("banked/questionbank")
public class QuestionBankController {
    @Autowired
    private QuestionBankService questionService;     //注入业务逻辑
    @Autowired
    private ExcelImporter excelImporter;
    //增
    @PostMapping("/add")
    public String add(@RequestBody QuestionBankEntity question){
        Integer i = questionService.add(question);
        if(i>0){
            return "success";
        }
        else {
            return "fail";
        }
    }
    // 删：根据ID删除题目
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Long id) {
        int i = questionService.delete(id);
        if(i>0){
            return "success";
        }
        else {
            return "fail";
        }
    }

    //查:根据Id获取题目
    @GetMapping("/{id}")
    public ResponseEntity<QuestionBankEntity> getQuestionById(@PathVariable Long id) {
        QuestionBankEntity question = questionService.search(id);
        return ResponseEntity.ok(question);
    }
    // 改：更新字典
    @PutMapping("/update")
    public String update(@RequestBody QuestionBankEntity question) {
        int i = questionService.update(question);
        if(i>0){
            return "success";
        }
        else {
            return "fail";
        }
    }
    //分页查询
    @GetMapping("/List")
    public IPage<QuestionBankEntity> List(@RequestBody QuestionBankEntityVo vo){
        return questionService.List(vo);
    }
    /**
     * 导入 Excel 文件中的题库数据
     *
     * @param file Excel 文件
     * @return 导入结果
     */
    // 导入 Excel 文件中的题库数据
    @PostMapping("/import")
    public ResponseEntity<String> importQuestions(@RequestParam("file") MultipartFile file) {
        try {
            // 将 MultipartFile 转换为本地文件并获取路径
            String filePath = System.getProperty("java.io.tmpdir") + "/" + file.getOriginalFilename();
            file.transferTo(new File(filePath));
            // 调用 Excel 导入方法
            int importedCount = excelImporter.importExcel(filePath);
            return ResponseEntity.ok("成功导入 " + importedCount + " 道题目");
        } catch (IOException e) {
            log.error("导入失败", e);
            return ResponseEntity.status(500).body("导入失败: " + e.getMessage());
        }
    }
}
